<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'
import { io } from 'socket.io-client'
import type { Socket } from 'socket.io-client'
import { onMounted } from 'vue'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import { onUnmounted } from 'vue'
import type { Message, TimeMessages } from '@/types/room'
import { MsgType } from '@/enums'
import { ref } from 'vue'

const userStore = useUserStore()
const route = useRoute()

// 累加的聊天记录
const list = ref<Message[]>([])

let socket: Socket
onMounted(() => {
  // 创建连接
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${userStore.user?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })
  // 监听连接创建成功的事件
  socket.on('connect', () => {
    console.log('连接创建成功')
  })
  // 监听连接失败的事件
  socket.on('error', (event) => {
    console.log('连接失败')
  })
  // 监听连接关闭的事件
  socket.on('disconnect', () => {
    console.log('连接关闭了')
  })

  // type ResType = {
  //   success: boolean
  //   code: number
  //   message: string
  //   data: TimeMessages[]
  // }

  // 接收聊天记录
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    // data：后端返回的树形结构数据
    // console.log(data)
    // arr：转换后的扁平化数组数据
    // arr：每次下拉刷新，获取到的历史聊天记录的数据
    const arr: Message[] = []
    data.forEach((item) => {
      // 处理时间
      arr.push({
        msgType: MsgType.Notify,
        msg: {
          content: item.createTime
        },
        createTime: item.createTime,
        id: item.createTime
      })
      // 处理每条消息
      arr.push(...item.items)
    })
    // console.log(arr)
    // 将每次下拉刷新，获取到的历史聊天记录的数据，累加到 list 的前面
    list.value.unshift(...arr)
    console.log(list)
  })
})
// 组件卸载时，关闭 socket 连接
onUnmounted(() => {
  socket.close()
})
</script>

<template>
  <div class="room-page">
    <!-- 导航栏 -->
    <cp-nav-bar title="问诊室" />
    <!-- 顶部状态栏 -->
    <room-status></room-status>
    <!-- 消息组件 -->
    <room-message v-for="item in list" :key="item.id" :item="item"></room-message>
    <!-- 底部操作栏 -->
    <room-action></room-action>
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
